#include "../DEHT/deht.h"
#include <string.h>
#include <stdlib.h>
#include "../global/misc.h"
#include "../global/global_auth.h"

enum ValidationStatus {
	SUCCESS,
	INVALID_INPUT,
	NOT_IN_DEHT
};


int handle_line(DEHT* d, char* line) {
	unsigned char output_buffer[32768] = {0}; /* a key's data is limited to 15 bits */
	unsigned char hash_buffer[30] = {0};
	int hash_length_in_bytes;
	int ret_val;

	if (strcmp(line, "quit") == 0 || strcmp(line, "quit\n") == 0) {
		lock_DEHT_files(d);
		exit(0);
	}

	if (!validate_hex_string(line)) {
		printf("Non hexa\n");
		return INVALID_INPUT;
	}

	if (strcmp(d->header.sDictionaryName, "MD5") == 0) {
		hash_length_in_bytes = MD5_OUTPUT_LENGTH_IN_BYTES;
	}
	else if (strcmp(d->header.sDictionaryName, "SHA1") == 0) {
			hash_length_in_bytes = SHA1_OUTPUT_LENGTH_IN_BYTES;
	}

	hexa2binary(line, hash_buffer, hash_length_in_bytes);

	ret_val = query_DEHT(d, (unsigned char*)hash_buffer, hash_length_in_bytes, output_buffer, 32768);

	switch(ret_val) {

	case DEHT_STATUS_NOT_NEEDED:
		printf("Sorry but this hash doesn't appears in pre-processing\n");
		return NOT_IN_DEHT;

	case DEHT_STATUS_FAIL:
		printf("operation failed\n");
		lock_DEHT_files(d);
		exit(1);

	default: /* if query succeeded */
		printf("Try to login with password \"");
		fwrite(output_buffer, sizeof(char), ret_val, stdout);
		printf("\"\n");
		return SUCCESS;
	}
}


int main(int argc, char* argv[]) {
	char line[257];
	DEHT* d;
	if (argc != 2) {
		printf("should be called with a parameter: prefix\n");
		return 1;
	}

	d = load_DEHT_from_files(argv[1], str_mod, keyTo64Bit);
	if (d == 0) {
		fprintf (stderr, "error loading DEHT \"%s\"\n", "prefix");
		return 1;
	}

	printf(">> ");
	while (fgets(line, 256, stdin) != 0) {
		if (line[strlen(line)-1] == '\n') { /* remove trailing \n */
			line[strlen(line)-1] = 0;
		}
		handle_line(d, line);
		printf(">> ");

	}
	lock_DEHT_files(d);
	free(d);
	return 0;
}

